<template>
  <view class="echart-container" :style="{ width: width, height: height }">
    <canvas type="2d" :id="canvasId" class="echart-canvas"></canvas>
  </view>
</template>

<script>
let echarts = null

export default {
  name: 'l-echart',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    canvasId: {
      type: String,
      default() {
        return `echart_${Math.random().toString(36).substr(2)}`
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  methods: {
    async init(ec) {
      echarts = ec
      const canvas = await this.getCanvas()
      if (!canvas) return
      
      const ctx = canvas.getContext('2d')
      const dpr = uni.getSystemInfoSync().pixelRatio
      canvas.width = canvas._width * dpr
      canvas.height = canvas._height * dpr
      ctx.scale(dpr, dpr)

      this.chart = echarts.init(canvas, null, {
        width: canvas._width,
        height: canvas._height,
        devicePixelRatio: dpr
      })
      
      canvas.setChart(this.chart)
    },
    async getCanvas() {
      return new Promise((resolve) => {
        uni.createSelectorQuery()
          .in(this)
          .select(`#${this.canvasId}`)
          .fields({ node: true, size: true })
          .exec((res) => {
            if (res[0]) {
              const canvas = res[0].node
              canvas._width = res[0].width
              canvas._height = res[0].height
              resolve(canvas)
            } else {
              resolve(null)
            }
          })
      })
    },
    setOption(option) {
      if (this.chart) {
        this.chart.setOption(option)
      }
    },
    clear() {
      if (this.chart) {
        this.chart.clear()
      }
    },
    dispose() {
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
    }
  },
  beforeDestroy() {
    this.dispose()
  }
}
</script>

<style lang="scss" scoped>
.echart-container {
  position: relative;
  
  .echart-canvas {
    width: 100%;
    height: 100%;
  }
}
</style> 